﻿/**************************************************************
 *
 * 唯一标识：9a35a5fe-eec9-4aa2-9435-21e997ecf21a
 * 命名空间：Sgr.UPMS.Application.Commands.Duties
 * 创建时间：2023/8/27 19:16:09
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：创建职务命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Queries;
using Sgr.Exceptions;
using Sgr.Generator;
using Sgr.UPMS.Domain.Duties;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Sgr.UPMS.Application.Commands.Duties
{
    /// <summary>
    /// 创建职务命令处理器
    /// </summary>
    public class CreateDutyCommandHandle : IRequestHandler<CreateDutyCommand, bool>
    {
        private readonly IDutyRepository _dutyRepository;
        private readonly ICurrentUser _currentUser;
        private readonly ISegmentNumIdGenerator _numberIdGenerator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dutyRepository">职务仓储</param>
        /// <param name="currentUser"></param>
        /// <param name="numberIdGenerator"></param>
        public CreateDutyCommandHandle(IDutyRepository dutyRepository,
            ICurrentUser currentUser,
           ISegmentNumIdGenerator numberIdGenerator)
        {
            _dutyRepository = dutyRepository ?? throw new ArgumentNullException(nameof(dutyRepository));
            _currentUser = currentUser ?? throw new ArgumentNullException(nameof(currentUser));
            _numberIdGenerator = numberIdGenerator ?? throw new ArgumentNullException(nameof(numberIdGenerator));
        }

        /// <summary>
        /// 处理创建职务命令
        /// </summary>
        /// <param name="request">命令请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<bool> Handle(CreateDutyCommand request, CancellationToken cancellationToken)
        {
            // 生成唯一编码
            string code = Guid.NewGuid().ToString("N");

            long orgId = QueryHelper.GetOrgId(_currentUser);

            // 检查职务名称唯一性
            bool nameIsUnique = await _dutyRepository.NameIsUniqueAsync(request.Name, null, orgId, cancellationToken);
            if (!nameIsUnique)
                throw new BusinessException($"职务名称“{request.Name}”已存在，请更换名称。");

            // 创建职务实体
            Duty duty = new Duty(
                code,
                request.Name,
                request.OrderNumber,
                request.Remarks,
                orgId)
            {
                Id = await _numberIdGenerator.GetUniqueIdAsync(UpmsConstant.DEFAULT_SEGMENT_KEY, cancellationToken)
            };
            duty.ChangeEntityStates(request.State);
            duty.MarkAsChanged();

            // 保存到仓储
            await _dutyRepository.InsertAsync(duty, cancellationToken);

            return true;
        }
    }
}